﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

/// <summary>
/// APIBuilder，生成C#文档工具
/// Add by yeshaowei,2016/12/21
/// </summary>
namespace APIBuilder
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            this.Icon = new Icon("Resources/ICO.ico");
            Init();

        }

        #region Methods

        /// <summary>
        /// 初始化控件
        /// </summary>
        private void Init()
        {
            this.FormClosing += Main_FormClosing;
            this.ParamView.ItemSelectionChanged += ParamView_ItemSelectionChanged;
            Common.InitData();
            this.MaximizeBox = false;
            this.ParamView.Columns.Add("参数名", 120, HorizontalAlignment.Left);
            this.ParamView.Columns.Add("参数描述", 500, HorizontalAlignment.Left);
            InitAPINameComBox();
        }



        private void InitAPINameComBox()
        {
            string[] files = Directory.GetFiles(Common.GetBaseURL() + Common.GetConfigByKey("APIURL"), "*.html");
            if (files.Length > 0)
            {
                for (int i = 0; i < files.Length; i++)
                {
                    APIName.Items.Add(Path.GetFileNameWithoutExtension(files[i]));
                }
                APIName.SelectedIndex = 0;
            }                  
         }
        /// <summary>
        /// 重新构建Index索引和Combox
        /// </summary>
        private void BindAPIName()
        {
            if(string.IsNullOrEmpty(Common.NewAPI))
             { return; }
            string indexRUL= Common.GetBaseURL() + Common.GetConfigByKey("IndexURL");
            if(File.Exists(indexRUL))
            {
               
                string[] files= Directory.GetFiles(Common.GetBaseURL() + Common.GetConfigByKey("APIURL"), "*.html");
                if(files.Length>0)
                {
                    //Index索引
                    string indexHTML = File.ReadAllText(indexRUL, Encoding.UTF8);
                    string appendHTML = string.Format("<li tar='Page/{0}'>{1}</li><!--NavHolder-->", Common.NewAPI + ".html", Common.NewAPI);
                    File.WriteAllText(indexRUL, indexHTML.Replace("<!--NavHolder-->", appendHTML), Encoding.UTF8);
                    indexHTML = string.Empty;
                    //Combox
                    APIName.Items.Add(Common.NewAPI);
                    Common.NewAPI = string.Empty;
                    APIName.SelectedIndex = 0;
                }
            }
            else
            {
                MessageBox.Show("Shitttter!找不到主要了，Index.html！", Common.Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 构建HTML
        /// </summary>
        /// <returns></returns>
        private string BuildHTML()
        {
            StringBuilder sb = new StringBuilder();
            StringBuilder paramsInput = new StringBuilder();
            //Btn按钮
            sb.AppendFormat("<input id='{0}' class='button01' type='button' value='{1}' />", FunName.Text.Trim() + "_Btn", FunName.Text.Trim());
            //Build Table
            sb.Append("<table class='funInfo'>");
            sb.AppendFormat("<tr><th>函数说明：</th><td>{0}</td></tr>", FunInfor.Text.Trim());
            sb.AppendFormat("<tr><th>JS API：</th><td class='js'>{0}</td></tr>", JSAPI.Text.Trim());
            sb.AppendFormat("<tr><th>C#原型：</th><td class='cSharp'>{0}</td></tr>", CSharp.Text.Trim());
            //Build Params
            if (Common.Params.Count > 0)
            {
                foreach (var key in Common.Params.Keys)
                {
                    sb.AppendFormat("<tr><th><span class='param'>{0}</span></th><td>{1}</td></tr>", key, Common.Params[key]);
                    //构建非可选参数文本域
                    if (Common.Params[key].IndexOf("(可选)") == -1)
                    {
                        paramsInput.AppendFormat("<p class='p2'>{0}&nbsp;<input id='{1}' class='text01' type='text'/></p>", key, FunName.Text.Trim() + "_" + key);
                    }
                }
                //Common.Params.Clear();
            }
            sb.AppendFormat("<tr><th>返回值：</th><td class='json'>{0}</td></tr>", ReturnVal.Text.Trim());
            sb.AppendFormat("<tr><th>JS回调：</th><td class='js'>{0}</td></tr>", string.IsNullOrEmpty(CallBack.Text.Trim())==true?"无":CallBack.Text.Trim());
            sb.Append("</table>");
            //非可选参数文本域
            sb.Append(paramsInput.ToString());
            paramsInput.Clear();
            //Result
            sb.AppendFormat("<p class='p2'>Result:</p><p class='p3' id='{0}'></p>", FunName.Text.Trim() + "_Result");
            //CallBack
            sb.AppendFormat("<p class='p2'>CallBack:</p><p class='p3' id='{0}'></p>", FunName.Text.Trim() + "_CallBack");
            sb.Append("<hr class='hr1' />\n<!--HTMLHolder-->");
            
            return sb.ToString();
        }
        /// <summary>
        /// 构建JS
        /// </summary>
        /// <returns></returns>
        private string BuildJS()
        {
            StringBuilder sb = new StringBuilder();
            StringBuilder param = new StringBuilder();
            string paramJS = string.Empty;
            //构建必选参数
            if (Common.Params.Count > 0)
            {
                foreach (var key in Common.Params.Keys)
                {
                    //构建必选参数JS
                    if (Common.Params[key].IndexOf("(可选)") == -1)
                    {
                        param.AppendFormat("$('#{0}').val(),", FunName.Text.Trim() + "_" + key);
                    }
                }
                if (!string.IsNullOrEmpty(param.ToString()))
                {
                    paramJS = param.ToString().Substring(0, param.ToString().Length - 1);
                }
            }
            //注册单击事件
            sb.Append("$('#" + FunName.Text.Trim() + "_Btn" + "').click(function(){var result=window.external." + APIName.Text.Trim() + "." + FunName.Text.Trim() + "(" + paramJS + ")" + ";$('#" + FunName.Text.Trim() + "_Result" + "').text(result);});\n");
            //定义回调事件
            if(!string.IsNullOrEmpty(CallBack.Text.Trim()))
            {
                sb.Append("function " + CallBack.Text.Trim() + "{$('#" + FunName.Text.Trim() + "_CallBack" + "').text(msg);}\n");
            }
            sb.Append("//JSHolder");
            return sb.ToString();
        }
        /// <summary>
        /// 参数列表绑定数据
        /// </summary>
        private void BindData()
        {
            this.ParamView.Items.Clear();
            if (Common.Params.Count > 0)
            {
                this.ParamView.BeginUpdate();
                ListViewItem lvi = null;            
                foreach (var key in Common.Params.Keys)
                {
                    lvi = new ListViewItem();
                    lvi.Text = key;
                    lvi.SubItems.Add(Common.Params[key]);
                    this.ParamView.Items.Add(lvi);
                }
                this.ParamView.EndUpdate();
            }
        }
        #endregion

        #region Form Call Back
        /// <summary>
        /// Form关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            Common.InitData();
        }
        /// <summary>
        /// 增改参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PAddBtn_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(PName.Text.Trim())||string.IsNullOrEmpty(PInfo.Text.Trim()))
            {
                MessageBox.Show("请完整信息！",Common.Caption,MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            string optional = "";
            if(IsOptional.Checked)
            {
                optional = "(可选)";
            }
            if (Common.Params.ContainsKey(PName.Text.Trim()))
            {
                Common.Params[PName.Text.Trim()] = PInfo.Text.Trim()+ optional;
            }
            else
            {
                Common.Params.Add(PName.Text.Trim(), PInfo.Text.Trim()+ optional);
            }
            BindData();
            PName.Text = "";
            PInfo.Text = "";
            IsOptional.Checked = false;
        }
        /// <summary>
        /// 删除参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelParam_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("确认删除参数吗?", Common.Caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question)==DialogResult.No)
            { return; }
            if (string.IsNullOrEmpty(PName.Text.Trim()))
            {
                MessageBox.Show("参数名不能为空！", Common.Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if(!Common.Params.ContainsKey(PName.Text.Trim()))
            {
                MessageBox.Show("未找到参数！", Common.Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Common.Params.Remove(PName.Text.Trim());
            BindData();
            PName.Text = "";
            PInfo.Text = "";
            IsOptional.Checked = false;
        }
        /// <summary>
        /// 参数列表选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ParamView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            PName.Text = e.Item.Text;
            PInfo.Text = e.Item.SubItems[1].Text.Replace("(可选)","");
            //如果是可选，则选中
            if(e.Item.SubItems[1].Text.IndexOf("(可选)")!=-1)
            {
                IsOptional.Checked = true;
            }
            else
            {
                IsOptional.Checked = false; ;
            }
        }
        /// <summary>
        /// 提交按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SubmitBtn_Click(object sender, EventArgs e)
        {
            try
            {
                //string template2 = File.ReadAllText(Common.GetBaseURL() + Common.GetConfigByKey("TemplateURL"), Encoding.UTF8);
                if (string.IsNullOrEmpty(APIName.Text.Trim())
                    || string.IsNullOrEmpty(FunName.Text.Trim())
                    || string.IsNullOrEmpty(FunInfor.Text.Trim())
                    || string.IsNullOrEmpty(CSharp.Text.Trim())
                    || string.IsNullOrEmpty(JSAPI.Text.Trim())
                    || string.IsNullOrEmpty(ReturnVal.Text.Trim())
                    )
                {
                    MessageBox.Show("Shitttter!你看红色文字了吗！", Common.Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                //查找文件是否存在,不存在则创建，存在则修改
                string path = Common.GetBaseURL() + Common.GetConfigByKey("APIURL") + APIName.Text.Trim() + ".html";
                if (File.Exists(path))
                {
                    string html = File.ReadAllText(path, Encoding.UTF8);
                    string newHtml = html.Replace("<!--HTMLHolder-->", BuildHTML()).Replace("//JSHolder", BuildJS());
                    File.WriteAllText(path, newHtml, Encoding.UTF8);
                    html = null;
                    newHtml = null;
                    MessageBox.Show("Shitttter!成功！", Common.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    string templateURL = Common.GetBaseURL() + Common.GetConfigByKey("TemplateURL");
                    //判断模板是否存在
                    if(File.Exists(templateURL))
                    {
                        string template = File.ReadAllText(Common.GetBaseURL() + Common.GetConfigByKey("TemplateURL"), Encoding.UTF8);
                    }
                    else
                    {
                        MessageBox.Show("Shitttter!找不到模板！", Common.Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, Common.Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            { }
        }
        /// <summary>
        /// 创建新API按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateNewAPI_Click(object sender, EventArgs e)
        {
            NewAPI api = new NewAPI();
            // api.Parent = this;
            api.FormClosed += Api_FormClosed;
            api.StartPosition = FormStartPosition.CenterParent;
            api.ShowDialog();
        }
        /// <summary>
        /// NewAPI关闭回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Api_FormClosed(object sender, FormClosedEventArgs e)
        {
            BindAPIName();
        }
        #endregion


    }
}
